package com.dongnam.quanly.ChiTietPhieuNhapXuat;

import java.io.IOException;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.primefaces.context.RequestContext;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.event.SelectEvent;

import com.dongnam.quanly.common.controller.ChiTietNhapXuatController;
import com.dongnam.quanly.common.model.ChiTietNhapXuat;
import com.dongnam.quanly.web.UserBean;
import com.dongnam.quanly.web.util.DateFormatUtil;
import com.dongnam.quanly.web.util.WebUtil;

@ManagedBean(name = "ChiTietNXBean")
@SessionScoped
public class AddChiTietNXBean implements Serializable{
	private static final long serialVersionUID = 1L;
	@ManagedProperty(value = "#{UserBean}")
	private UserBean userBean;
	private boolean isEdit = false;
	//controller
	private ChiTietNhapXuatController chiTietNhapXuatController;
	//edit
	private ChiTietNhapXuat selectedHoaDon;
	private List<ChiTietNhapXuat> listChiTietNhapXuat;
	private List<ChiTietNhapXuat> filteredPhieuNhapXuat;
	//add
	private ChiTietNhapXuat addChiTietNhapXuat;
	private Date ngayPhatHanhUpload;
	private Date ngayThucXuat;
	private int soHDStart;
	private int soHDEnd;
	public AddChiTietNXBean(){
		super();
		addChiTietNhapXuat = new ChiTietNhapXuat();
		listChiTietNhapXuat=new ArrayList<ChiTietNhapXuat>();
		//loadPhieuNhapXuat();
		soHDStart=1;
	}
	public UserBean getUserBean() {
		return userBean;
	}
	public void setUserBean(UserBean userBean) {
		this.userBean = userBean;
	}
	public boolean isEdit() {
		return isEdit;
	}
	public void setEdit(boolean isEdit) {
		this.isEdit = isEdit;
	}
	public ChiTietNhapXuatController getChiTietNhapXuatController() {
		if(chiTietNhapXuatController==null){
			chiTietNhapXuatController=new ChiTietNhapXuatController();
		}
		return chiTietNhapXuatController;
	}
	public void setChiTietNhapXuatController(
			ChiTietNhapXuatController chiTietNhapXuatController) {
		this.chiTietNhapXuatController = chiTietNhapXuatController;
	}
	public ChiTietNhapXuat getSelectedHoaDon() {
		return selectedHoaDon;
	}
	public void setSelectedHoaDon(ChiTietNhapXuat selectedHoaDon) {
		this.selectedHoaDon = selectedHoaDon;
	}
	public List<ChiTietNhapXuat> getListChiTietNhapXuat() {
		if(listChiTietNhapXuat==null){
			listChiTietNhapXuat= getChiTietNhapXuatController().findAll();
		}
		return listChiTietNhapXuat;
	}
	
	public Date getNgayPhatHanhUpload() {
		return ngayPhatHanhUpload;
	}
	public void setNgayPhatHanhUpload(Date ngayPhatHanhUpload) {
		this.ngayPhatHanhUpload = ngayPhatHanhUpload;
	}
	
	
	public Date getNgayThucXuat() {
		return ngayThucXuat;
	}
	public void setNgayThucXuat(Date ngayThucXuat) {
		this.ngayThucXuat = ngayThucXuat;
	}
	public void setListChiTietNhapXuat(List<ChiTietNhapXuat> listChiTietNhapXuat) {
		this.listChiTietNhapXuat = listChiTietNhapXuat;
	}
	public ChiTietNhapXuat getAddChiTietNhapXuat() {
		return addChiTietNhapXuat;
	}
	public void setAddChiTietNhapXuat(ChiTietNhapXuat addChiTietNhapXuat) {
		this.addChiTietNhapXuat = addChiTietNhapXuat;
	}
	public void loadPhieuNhapXuat() {
		this.listChiTietNhapXuat = getChiTietNhapXuatController().findAll("updateDate", "DESCENDING");
	}
	public void loadHDtheoNgayThucXuat(){
		this.listChiTietNhapXuat = getChiTietNhapXuatController().findHDNgayTX(ngayThucXuat);
	}
	public void reloadHDtheoNgayThucXuat(Date ntx){
		System.err.println(ntx);
		listChiTietNhapXuat = getChiTietNhapXuatController().findHDNgayTX(ntx);
		System.err.println(listChiTietNhapXuat.size());
	}
	
	public int getSoHDStart() {
		return soHDStart;
	}
	public void setSoHDStart(int soHDStart) {
		this.soHDStart = soHDStart;
	}
	public int getSoHDEnd() {
		return soHDEnd;
	}
	public void setSoHDEnd(int soHDEnd) {
		this.soHDEnd = soHDEnd;
	}
	public List<ChiTietNhapXuat> getFilteredPhieuNhapXuat() {
		return filteredPhieuNhapXuat;
	}
	
	public void setFilteredPhieuNhapXuat(List<ChiTietNhapXuat> filteredPhieuNhapXuat) {
		this.filteredPhieuNhapXuat = filteredPhieuNhapXuat;
	}
	public void addCTNX(){
		RequestContext requestContext = RequestContext.getCurrentInstance();
		FacesContext context = FacesContext.getCurrentInstance();
		try{
			if(isEdit){
				getChiTietNhapXuatController().makeTransient(addChiTietNhapXuat);
				getChiTietNhapXuatController().makePersistent(addChiTietNhapXuat);
//				loadPhieuNhapXuat();
				reloadHDtheoNgayThucXuat(addChiTietNhapXuat.getNgayThucXuat());
			}
			else{
				getChiTietNhapXuatController().makePersistent(addChiTietNhapXuat);
				reloadHDtheoNgayThucXuat(addChiTietNhapXuat.getNgayThucXuat());
			}
			requestContext.addCallbackParam("opSuccess", true);
			WebUtil.redirect("/pages/nhapxuat/NhapXuatKho.xhtml");
		} catch (Exception e) {
			e.printStackTrace();
			requestContext.addCallbackParam("opSuccess", false);
		}
	}
	public void handlesoHDEvent(){
		
	}
	 public void selectPNX(ChiTietNhapXuat ctnx){
		 this.addChiTietNhapXuat=ctnx;
		 isEdit=true;
	 }
	public void notifyAdd(){
		isEdit=false;
		resetFormAdd();
	}
	public void resetFormAdd(){
		addChiTietNhapXuat=new ChiTietNhapXuat();
	}
	 public void onLoadSelect(SelectEvent event) {

        FacesContext facesContext = FacesContext.getCurrentInstance();
        SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
        facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Date Selected", format.format(event.getObject())));
        ngayThucXuat= (Date) event.getObject();

//        getChiTietNhapXuatController().findHDNgayTX(ngayThucXuat);
        
//        System.out.println(ngayPhatHanhUpload);
 }
	 public void LoadHD(){
		 reloadHDtheoNgayThucXuat(ngayThucXuat);
	 }
	 public void onDateSelect(SelectEvent event) {
	        FacesContext facesContext = FacesContext.getCurrentInstance();
	        SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
	        facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Date Selected", format.format(event.getObject())));
	        ngayPhatHanhUpload= (Date) event.getObject();
//	        System.out.println(ngayPhatHanhUpload);

	 }

	public void handleFileUpload(FileUploadEvent event) {
		// ToDo
		List<ChiTietNhapXuat> list = new ArrayList<ChiTietNhapXuat>();	
		DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
		DateFormat tf = new SimpleDateFormat("HH:mm");
		boolean rollback = false;
		try {
			HSSFWorkbook workbook= new HSSFWorkbook(event.getFile().getInputstream());
			HSSFSheet sheet= workbook.getSheetAt(0);
			Iterator<Row> rowIterator = sheet.iterator();
			for(int i=0;i<soHDStart;i++){
				rowIterator.next();
			}
		    while(rowIterator.hasNext()&& soHDStart<soHDEnd+1) {
		    	Row row = rowIterator.next();
		    	Cell cell_soHD=row.getCell(1);
		    	Cell cell_ngayPhatHanh=row.getCell(2);
				Cell cell_soXe=row.getCell(3);
				Cell cell_taiXe=row.getCell(4);
				Cell cell_gioTX=row.getCell(5);
				Cell cell_donHang=row.getCell(6);
				Cell cell_soLuongTX= row.getCell(7);
//				System.out.println(tf.format(cell_gioTX.getDateCellValue())); 
//				System.out.println(df.format(cell_ngayPhatHanh.getDateCellValue()));

		        ChiTietNhapXuat pnx = new ChiTietNhapXuat();
				pnx.setSTT(soHDStart);
				pnx.setSoHoaDon(cell_soHD.getStringCellValue());
				pnx.setNgayPhatHanh(DateFormatUtil.String2Date("dd/MM/yyyy",df.format(cell_ngayPhatHanh.getDateCellValue())));
				pnx.setSoXe(cell_soXe.getStringCellValue());
				pnx.setNguoiNhan(cell_taiXe.getStringCellValue());
				pnx.setGioThucXuat(DateFormatUtil.String2Date("HH:mm",tf.format(cell_gioTX.getDateCellValue())));
				pnx.setNgayThucXuat(ngayPhatHanhUpload);
				pnx.setSoluongTX((float) cell_soLuongTX.getNumericCellValue());
				pnx.setDonHang(cell_donHang.getStringCellValue());
				list.add(pnx);
		        soHDStart++;
		    }
		} catch (IOException e1) {
			rollback = true;
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		if (!rollback) {
			getChiTietNhapXuatController().batchSaveOrUpdate(list);
		}
	
		reloadHDtheoNgayThucXuat(ngayPhatHanhUpload);
//		Workbook w;
//		boolean rollback = false;
//		List<ChiTietNhapXuat> list = new ArrayList<ChiTietNhapXuat>();	
//		try {
//			w = Workbook.getWorkbook(event.getFile().getInputstream());
//			// Get the first sheet
//			Sheet sheet = w.getSheet(0);
//			// Loop over first 10 column and lines
//			//sheet.getRows();
//			int row =soHDStart;
//			for (; row <soHDEnd+1; row++) {
//
//				Cell cell_soHD=sheet.getCell(1,row);
//				Cell cell_ngayPhatHanh= sheet.getCell(2, row);;
//				Cell cell_soXe=sheet.getCell(3, row);
//				Cell cell_taiXe=sheet.getCell(4, row);
//				Cell cell_gioTX=sheet.getCell(5, row);
//				Cell cell_donHang=sheet.getCell(6, row);
//				Cell cell_soLuongTX= sheet.getCell(7, row);
//				
//				ChiTietNhapXuat pnx = new ChiTietNhapXuat();
////				System.out.println(cell_soHD.getContents());
////				System.out.println(cell_ngayPhatHanh.getContents());
////				System.out.println(cell_soXe.getContents());
////				System.out.println(cell_taiXe.getContents());
//				System.out.println(cell_gioTX.getCellFormat());
////				System.out.println(cell_donHang.getContents());
////				System.out.println(addChiTietNhapXuat.getNgayPhatHanh());
//				pnx.setSTT(row);
//				pnx.setSoHoaDon(cell_soHD.getContents());
//				pnx.setNgayPhatHanh(DateFormatUtil.String2Date("dd/MM/yyyy",cell_ngayPhatHanh.getContents()));
//				pnx.setSoXe(cell_soXe.getContents());
//				pnx.setNguoiNhan(cell_taiXe.getContents());
//				pnx.setGioThucXuat(DateFormatUtil.String2Date("h:mm",cell_gioTX.getContents()));
//				pnx.setNgayThucXuat(ngayPhatHanhUpload);
//				pnx.setSoluongTX(Integer.parseInt(cell_soLuongTX.getContents().replace(",","")));
//				pnx.setDonHang(cell_donHang.getContents());
//				list.add(pnx);
//			}
//		} catch (BiffException | IOException e) {
//			e.printStackTrace();
//			rollback = true;
//			FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unsuccessful : Database error : "
//					+ e.getMessage(), "");
//			FacesContext.getCurrentInstance().addMessage(null, msg);
//		}
//
//		if (!rollback) {
//			getChiTietNhapXuatController().batchSaveOrUpdate(list);
//		}
//
//		listChiTietNhapXuat=list;
	}
//	 private String getContents(Cell cell) {
//		    DateCell dCell=null;
//		    if(cell.getType() == CellType.DATE)
//		    {
//		    	
//		      dCell = (DateCell)cell;
//		      // System.out.println("Value of Date Cell is: " + dCell.getDate()); 
//		      // ==> Value of Date Cell is: Thu Apr 22 02:00:00 CEST 2088
//		      SimpleDateFormat sdf=new SimpleDateFormat("HH:mm");  
//		      // System.out.println(sdf.format(dCell.getDate()));
//		      // ==> 2088-04-22   
//		      System.out.println(cell.toString());
//		      return sdf.format(dCell.getDate());
//		    }
//		    // possibly manage other types of cell in here if needed for your goals   
//		    // read more: http://www.quicklyjava.com/reading-excel-file-in-java-datatypes/#ixzz2fYIkHdZP 
//		    return cell.getContents();
//		}
}
